//
//  HTEmotionModelManager.swift
//  表情键盘
//
//  Created by whtapple on 4/3/16.
//  Copyright © 2016 whtapple. All rights reserved.
//

import UIKit

class HTEmotionModelManager: NSObject {
    //单例
    static let sharedManager = HTEmotionModelManager()
//    //归档路径
//    let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!  + "/recentemotions.plist"
    private override init() {
        super.init()
    }
    static let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
    // 懒加载packages
    lazy var packages: [HTEmotionPackageModel] = self.loadPackages()
    //加载表情包
    func loadPackages() -> [HTEmotionPackageModel]{
        var packages = [HTEmotionPackageModel]()
        let emotions = readRcentEmotionsFromSandBox()
        let recentPackage = HTEmotionPackageModel(id: "", group_name_cn: "最近", emoticons: emotions)
        packages.append(recentPackage)
        packages.append(loadPackageModel("com.sina.default"))
        packages.append(loadPackageModel("com.apple.emoji"))
        packages.append(loadPackageModel("com.sina.lxh"))
        return packages
    }
    
    //加载一个表情包
    private func loadPackageModel(id: String) -> HTEmotionPackageModel{
        let infoPath = HTEmotionModelManager.path + "/" + id + "/" + "info.plist"
        let infoDict = NSDictionary(contentsOfFile: infoPath)!
        let group_name_cn = infoDict["group_name_cn"] as! String
        let emotionsArray = infoDict["emoticons"] as! [[String: String]]
        var emotions = [HTEmotionModel]()
        for dict in emotionsArray{
            emotions.append(HTEmotionModel(id: id, dict: dict))
        }
        return HTEmotionPackageModel(id: id, group_name_cn: group_name_cn, emoticons: emotions)
    }
    //MARK: -最近表情
    //最近表情
    func addfavorate(model: HTEmotionModel){
        //获取数组
        var recentemotions = packages[0].pageemotions[0]
        //遍历得到相同的图标
         let containEmotions = recentemotions.filter { (e) -> Bool in
            //判断是 emoji表情，就找出和表情 code相等的
            if model.emoji != nil{
                return model.code == e.code
                //不是 emoji表情，就找名字相等的
            }else{
                return model.chs == e.chs
            }
        }
        //判断是否有相同的图标
        if let sameEmotion = containEmotions.first{
            //有的话找出其下标
            let index = recentemotions.indexOf(sameEmotion)
            //删除这个下标的元素
            recentemotions.removeAtIndex(index!)
        }
        //将图标加入数组
        recentemotions.insert(model, atIndex: 0)
        //当超过时，删除最后一个
        while recentemotions.count > 20{
            recentemotions.removeLast()
        }
        //给模型赋值
        packages[0].pageemotions[0] = recentemotions
        saveRecentEmotionsToSandBox(packages[0].pageemotions[0])
//        saveRecentEmotionsToSandBox( packages[0].pageemotions[0])
    }
    let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/recent.plist"
    
     //存入沙盒和从沙盒中取出来
    func saveRecentEmotionsToSandBox(emotions: [HTEmotionModel]){
        NSKeyedArchiver.archiveRootObject(emotions, toFile: path)
    }
    func readRcentEmotionsFromSandBox() -> [HTEmotionModel]{
        if let recentEmotions = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [HTEmotionModel]{
            return recentEmotions
        }else{
            return [HTEmotionModel]()
        }
    }
//    //归档存入沙盒
//    func saveRecentEmotionsToSandBox(emotions:[HTEmotionModel]){
//        NSKeyedArchiver.archiveRootObject(emotions, toFile: path)
////        print("\(path)")
//    }
//    //解档拿出数据
//    func filefromSandBox() -> [HTEmotionModel]{
//        //看看有没有数据，有的话就拿出来，没有就返回空数组
//        if let emotions = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [HTEmotionModel]{
//            return emotions
//        }else{
//            return [HTEmotionModel]()
//        }
//    }
    
}
